

//init
$(document).ready(function () {
    init()
})

// kp version
function init(){
    let priceList = $('.priceSell')
    console.log(priceList)
    let numList = $('.itemNum')
    let type = $('.itemType')
    console.log(numList)
    let tmp = parseFloat('0.00')
    let tmp1 = parseFloat('0.00')
    let mem= $('.member1')
    let mem1=parseInt(mem[0].value)
    console.log(mem1)
    for (let i = 0;i<priceList.length;++i){
        //有个￥和空格
        let price = parseFloat(priceList[i].innerText.substring(1))
        console.log(price)
        let num = parseInt(numList[i].value)
        let type1 = parseInt(type[i].value)
        console.log(type1)
        if(type1==2){
            tmp+=(price*num*0.9)
        }else {
            tmp += (price * num)
        }
        tmp1 += (price * num)
        console.log(tmp)
    }
    console.log(tmp)
    $('#in-payment').text(tmp1.toFixed(2))
    $('#member-payment').text(tmp.toFixed(2))
    if(mem1==0){$('#in-member').text("您不是会员，不能享用折扣。")}
    else {$('#in-member').text("")}
}


// my version
// function init(){
//     let priceList = $('.priceSell')
//     console.log(priceList)
//     let numList = $('.itemNum')
//     console.log(numList)
//     let tmp = parseFloat('0.00')
//     for (let i = 0;i<priceList.length;++i){
//         //有个￥和空格
//         let price = parseFloat(priceList[i].innerText.substring(1))
//         console.log(price)
//         let num = parseInt(numList[i].value)
//         console.log(num)
//         tmp+=(price*num)
//         console.log(tmp)
//     }
//     console.log(tmp)
//     $('#in-payment').text(tmp.toFixed(2))
// }

function checkAddress() {
    if ($('#useSavedAddress').prop("checked")==false &&
        $('#addr-detail').val()=="") {
        alert("请完善详细地址！")
        return false
    }
}



// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
    const o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (const k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}



$('#fin-submit').click(function () {
    const now = (new Date()).Format("yyyy-MM-dd hh:mm:ss")
    let tag = $("#in-member2").val()
    console.log("tag:"+tag)
    if(tag==1){
        tag = "Yes"
    }
    const indent = {
        "payment":$('#in-payment').text(),
        "paymentType":$('#online').prop('checked')==true?1:2,
        //默认邮费10
        "postFee":"10.00",
        // "status":"",
        // "userId": $('#user-id').val(),
        "buyerMessage":$('#in-msg').val(),
        "buyerName":$("#in-name").val(),
        "phone":$("#in-phone").val(),
        "addressId":$('#useSavedAddress').prop('checked')==true?$('#in-address').find('option:selected').val():"",
        "createTime": now,
        "updateTime": now
    }
    console.log(indent)
    console.log(JSON.stringify(indent))
    $.ajax({
        //是否异步(执行后面js
        async: true,
        type: "post",
        url: "/cart/payment",
        dataType: "text",
        contentType: 'application/json; charset=utf-8',
        // data: address,
        data: JSON.stringify(indent),
        success: function (res) {
            console.log(res)
            window.location.href="/indent/deal-success"
            alert("交易成功");
            window.location.href="/cart/invoice?indentId="+res+"&tag="+tag;
            // window.location.href="/cart/invoice?indentId="+res
        },
        error: function (res) {
            console.log(res)
            alert("交易失败");
            window.location.href="/indent/deal-failure"
        }
    });
})

$('#save-addr').click(function () {
    //不然两个时间会有点误差
    const now = (new Date()).Format("yyyy-MM-dd hh:mm:ss")
    const address = {
        "userId": "[[${session.user.id}]]",
        "userName": $("#in-name").val(),
        "tel": $("#in-phone").val(),
        "streetName": $("#addr-province").find("option:selected").val() +
            $('#addr-city').val() +
            $('#addr-area').val() +
            $('#addr-detail').val(),
        "isDefault": $('#is-default').is(':checked') == true?1:0,
        "createdTime": now,
        "updatedTime": now
    }
    console.log(address)
    console.log(JSON.stringify(address))
    $.ajax({
        //是否异步(执行后面js
        async: true,
        type: "post",
        url: "/address/add",
        dataType: "text",
        contentType: 'application/json; charset=utf-8',
        // data: address,
        data: JSON.stringify(address),
        success: function (res) {
            console.log(res)
            alert("保存成功");

        },
        error: function () {
            alert("请求失败");

        }
    });
})

$('#useSavedAddress').click(function () {
    if ($('#useSavedAddress').prop('checked')) {
        $('.address-new').css('display', 'none')
    }else {
        $('.address-new').css('display', 'inline')
    }
})


$(function(){
    /*demo1
    ***默认设置
    */
    // $('#demo1').citys();
    // /*demo2
    // ***根据区划代码初始化
    // */
    // $('#demo2').citys({
    //     code: '510116'
    // });
    /*demo3
    ***根据地区名称进行初始化
    */
    $('#address_p').citys({
        type: 'name',
        province: '广东省',
        city: '广州市',
        area: '海珠区'
    });
    console.log('city init...')
})
